package esay.array;

/**
 * 数独有效性
 * @author ruizhou
 * @date 26.02.2018
 */
public class ValidSudoku {
    private static boolean isValidSudoku(char[][] board) {
        for (int i = 0; i < 9; ++i) {
            boolean[] row = new boolean[9];
            boolean[] col = new boolean[9];
            boolean[] grid = new boolean[9];
            for (int j = 0; j < 9; ++j) {
                if (board[i][j] != '.') {
                    int rowIndex = board[i][j] - '1';
                    if (row[rowIndex]) {
                        return false;
                    }
                    row[rowIndex] = true;
                }
                if (board[j][i] != '.') {
                    int colIndex = board[j][i] - '1';
                    if (col[colIndex]) {
                        return false;
                    }
                    col[colIndex] = true;
                }
                if (board[j / 3 + (i / 3) * 3][(i % 3) * 3 + j % 3] != '.') {
                    int gridIndex = board[j / 3 + (i / 3) * 3][(i % 3) * 3 + j % 3] - '1';
                    if (grid[gridIndex]) {
                        return false;
                    }
                    grid[gridIndex] = true;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        char[][] board = {{'.','8','7','6','5','4','3','2','1'},
                          {'2','.','.','.','.','.','.','.','.'},
                          {'3','.','.','.','.','.','.','.','.'},
                          {'4','.','.','.','.','.','.','.','.'},
                          {'5','.','.','.','.','.','.','.','.'},
                          {'6','.','.','.','.','.','.','.','.'},
                          {'7','.','.','.','.','.','.','.','.'},
                          {'8','.','.','.','.','.','.','.','.'},
                          {'9','.','.','.','.','.','.','.','.'}};
        System.out.println(isValidSudoku(board));
    }
}
